package com.samuel.basics.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.samuel.basics.constant.CommonConstant;
import com.samuel.basics.model.BaseResponse;
import com.samuel.basics.service.WeChatService;
import com.samuel.basics.utils.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class WeChatServiceImpl implements WeChatService {

    private static final String URL = "https://api.weixin.qq.com/cgi-bin";
    private static final String APP_ID = "wx3d8ee18c6c611ed9";
    private static final String SECRET = "0bd84c92024ff54faf57bac8822516f5";



    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public BaseResponse getAccessToken() {
        // 从Redis中获取accessToken
        String s = stringRedisTemplate.opsForValue().get(CommonConstant.WeChat.ACCESS_TOKEN_REDIS_KEY);
        if (StringUtils.isNotBlank(s)) {
            return new BaseResponse(CommonConstant.Code.SUCCESS_CODE, "从redis中获取accessToken成功！", s);
        }
        // 通过接口获取accessToken
        JSONObject jsonObject = accessToken();
        if (null != jsonObject.get(CommonConstant.WeChat.ERROR_CODE)) {
            // 失败
            return new BaseResponse(CommonConstant.Code.FAIL_CODE, "从微信官网中获取accessToken失败！" +
                    jsonObject.getString(CommonConstant.WeChat.ERROR_MSG));
        }
        // 成功
        stringRedisTemplate.opsForValue().set(CommonConstant.WeChat.ACCESS_TOKEN_REDIS_KEY, jsonObject.getString(CommonConstant.WeChat.ACCESS_TOKEN),
                jsonObject.getLongValue(CommonConstant.WeChat.EXPIRES_IN), TimeUnit.SECONDS);
        return new BaseResponse(CommonConstant.Code.SUCCESS_CODE, "从微信官网中获取accessToken成功！",
                jsonObject.getString(CommonConstant.WeChat.ACCESS_TOKEN));
    }

    @Override
    public BaseResponse loginQrCode(String accessToken) {
        String url = URL + "/qrcode/create?access_token=" + accessToken;
        String params = "{\"expire_seconds\": 604800, \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"test_han\"}}}";
        try {
            String s = HttpClientUtil.doPostSSL(url, params);
            if (StringUtils.isBlank(s)) {
                throw new RuntimeException("网络异常！");
            }
            if (s.contains(CommonConstant.WeChat.ERROR_CODE)) {
                return new BaseResponse(CommonConstant.Code.FAIL_CODE, "获取临时二维码失败！" + s);
            }
            return new BaseResponse(CommonConstant.Code.SUCCESS_CODE, "获取临时二维码成功！", s);
        } catch (Exception e) {
            return new BaseResponse(CommonConstant.Code.FAIL_CODE, "获取临时二维码失败！" + e.getMessage());
        }


    }

    @Override
    public BaseResponse loginLimitQrCode(String accessToken) {
        String url = URL + "/qrcode/create?access_token=" + accessToken;
        String params = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"test_han_limit\"}}}";
        try {
            String s = HttpClientUtil.doPostSSL(url, params);
            if (StringUtils.isBlank(s)) {
                throw new RuntimeException("网络异常！");
            }
            if (s.contains(CommonConstant.WeChat.ERROR_CODE)) {
                return new BaseResponse(CommonConstant.Code.FAIL_CODE, "获取永久二维码失败！" + s);
            }
            return new BaseResponse(CommonConstant.Code.SUCCESS_CODE, "获取永久二维码成功！", s);
        } catch (Exception e) {
            return new BaseResponse(CommonConstant.Code.FAIL_CODE, "获取永久二维码失败！" + e.getMessage());
        }
    }

    /**
     * 微信获取accessToken
     * @return JSON串
     */
    private JSONObject accessToken() {
        String url = URL + "/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + SECRET;
        String result = HttpClientUtil.getHttps(url);

        if (StringUtils.isBlank(result)) {
            // throw new (500, "获取accessToken失败！原因：网络异常！");
        }
        return JSONObject.parseObject(result);
    }
}
